//
//  MoneyViewController.m
//  V-Learn
//
//  Created by Apple on 2019/5/30.
//  Copyright © 2019 yxk. All rights reserved.
//

#import "MoneyViewController.h"
// 1.首先导入支付包
#import <StoreKit/StoreKit.h>
#import "ZSDTCoreTextCell.h"
#import "ZSDTCoreTextTools.h"
@interface MoneyViewController ()<UITextViewDelegate,SKPaymentTransactionObserver,SKProductsRequestDelegate,UITableViewDelegate,UITableViewDataSource,DTAttributedTextContentViewDelegate,DTLazyImageViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIView *footerView;
@property (nonatomic, strong) UILabel *totalLab;/**金额*/
@property (nonatomic, strong) UIButton *firstBtn;
@property (nonatomic, strong) UIButton *thirdBtn;
@property (nonatomic, strong) UIButton *secodBtn;
@property (nonatomic, strong) UIButton *fourthBtn;
@property (nonatomic, strong) UIButton *fivethBtn;
@property (nonatomic, strong) UIButton *sixthBtn;
@property (nonatomic, strong) UIButton *sureBtn;/**确认按钮*/
@property (nonatomic, strong) NSString *resutltPrice;

@property(nonatomic,strong)NSMutableArray *productIDArray;
@property(nonatomic,strong)NSString *productID;/**产品id*/
@property (nonatomic, strong) UITextView *contenTextView;/**文本展示*/

//普通单元格与富文本单元格
@property (nonatomic, copy) NSString *cellID_Normal;
@property (nonatomic, copy) NSString *cellID_DTCoreText;

//类似tabelView的缓冲池，用于存放图片大小
@property (nonatomic, strong) NSCache *imageSizeCache;
@property (nonatomic,strong)NSCache *cellCache;
@property (nonatomic, strong) NSString *htmlString;
@property (nonatomic, strong) NSArray  *dataSource;
@property (nonatomic,assign)BOOL isScrolling;
@property (nonatomic,assign)CGFloat currenttime;
@property (nonatomic, strong) NSString  *hourId;//当前课程id

@end

@implementation MoneyViewController
- (UITextView *)contenTextView{
    if (!_contenTextView) {
        _contenTextView = [[UITextView alloc] init];
        _contenTextView.delegate = self;
    }
    return _contenTextView;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, LBNAVBAR_HEIGHT, ScreenW, ScreenH-LBNAVBAR_HEIGHT) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}
- (void)checkRequesntServiceData{
    [WYHXNetWorkManager post:WKCheckMoney_WKURL params:@{@"token":[UserModel getUserModel].token} completionHandler:^(id responseObj, NSError *error) {
        NSString *code = responseObj[@"code"];
        NSString *content = responseObj[@"data"][@"content"];
        if ([code integerValue]==200) {
            NSLog(@"%@",responseObj);
            self.htmlString = content;
            //保存余额
            NSString *string = [NSString stringWithFormat:@"%@",responseObj[@"data"][@"userMoney"]];
            [[NSUserDefaults standardUserDefaults] setObject:string forKey:@"userMoney"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[string stringByAppendingString:@" 乐学币"]];
            NSRange range1 = [[str string] rangeOfString:@"0"];
            [str addAttribute:NSForegroundColorAttributeName value:rgb(233,84,18) range:range1];
            [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:28] range:range1];
            NSRange range2 = [[str string] rangeOfString:@"乐学币"];
            [str addAttribute:NSForegroundColorAttributeName value:rgb(153,153,153) range:range2];
            [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13] range:range2];
            self.totalLab.attributedText = str;
        }
        [self.tableView reloadData];
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"我的钱包";
    [self.view addSubview:self.tableView];
    
    
    _imageSizeCache = [[NSCache alloc] init];
    _cellCache = [[NSCache alloc] init];
    _cellCache.totalCostLimit = 10;
    _cellCache.countLimit = 10;
    
    
    //创建头部视图
    [self setupHeaderViewSubView];
    
    //
//    [self setupFooterSubView];
    
    //plist 获取产品
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"productIDS" ofType:@"plist"];
    self.productIDArray =  [[NSMutableArray alloc] initWithContentsOfFile:plistPath];

    // 4.设置支付服务
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    
    //查询余额接口
    [self checkRequesntServiceData];
    
}
- (void)setupHeaderViewSubView{
    self.headerView = [[UIView alloc] init];
    self.headerView.frame = CGRectMake(0, 0, ScreenW, 435*ScaleX);
    self.tableView.tableHeaderView = self.headerView;
    
    
    self.totalLab = [UILabel labelWithText:@"862" andTextColor:rgb(233,84,18) andName:nil andFontSize:28*ScaleX];
    [self.headerView addSubview:self.totalLab];
    [self.totalLab makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.headerView);
//        make.centerY.mas_equalTo(self.headerView);
        make.top.mas_equalTo(43*ScaleX);
    }];
    NSString *string = @"0";
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[string stringByAppendingString:@" 乐学币"]];
    NSRange range1 = [[str string] rangeOfString:@"0"];
    [str addAttribute:NSForegroundColorAttributeName value:rgb(233,84,18) range:range1];
    [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:28] range:range1];
    NSRange range2 = [[str string] rangeOfString:@"乐学币"];
    [str addAttribute:NSForegroundColorAttributeName value:rgb(153,153,153) range:range2];
    [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13] range:range2];
    self.totalLab.attributedText = str;

    
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 50;
    self.tableView.tableFooterView = [UIView new];
    
    UIView *smallView = [[UIView alloc] init];
    smallView.backgroundColor = rgb(242,242,242);
    [self.headerView addSubview:smallView];
    [smallView makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.totalLab.mas_bottom).mas_equalTo(56*ScaleX);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(5*ScaleX);
    }];
    
    
    UIImageView *smallIcon = [[UIImageView alloc] init];
    smallIcon.image = [UIImage imageNamed:@"wanke_chongzhi"];
    [self.headerView addSubview:smallIcon];
    [smallIcon makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15*ScaleX);
        make.top.mas_equalTo(smallView.mas_bottom).mas_equalTo(19*ScaleX);
        make.size.mas_equalTo(CGSizeMake(15*ScaleX, 15*ScaleX));
    }];
    
    UILabel *chongzhiLab = [UILabel labelWithText:@"充值" andTextColor:rgb(51,51,51) andName:nil andFontSize:16*ScaleX];
    [self.headerView addSubview:chongzhiLab];
    [chongzhiLab makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(smallIcon.mas_right).mas_equalTo(6*ScaleX);
        make.centerY.mas_equalTo(smallIcon);
    }];
    
    UIButton *firstBtn = [[UIButton alloc] init];
    firstBtn.tag = 2001;
    self.firstBtn = firstBtn;
    [firstBtn setTitle:@"6 乐学币" forState:UIControlStateNormal];
    firstBtn.backgroundColor = rgb(233,84,18);
    [firstBtn addTarget:self action:@selector(clickPriceBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    [self setupButton:firstBtn];
    self.resutltPrice = @"6.00";
    
    [self.headerView addSubview:firstBtn];
    [firstBtn makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(23*ScaleX);
        make.top.mas_equalTo(chongzhiLab.mas_bottom).mas_equalTo(20*ScaleX);
        make.size.mas_equalTo(CGSizeMake(100*ScaleX, 34*ScaleX));
    }];
    
    UIButton *thirdBtn = [[UIButton alloc] init];
    thirdBtn.tag = 2003;
    self.thirdBtn = thirdBtn;
    [thirdBtn setTitle:@"68乐学币" forState:UIControlStateNormal];
    thirdBtn.titleLabel.font = [UIFont systemFontOfSize:15*ScaleX];
    thirdBtn.backgroundColor = rgb(253,238,231);
    [self setupButton:thirdBtn];
    
    [thirdBtn addTarget:self action:@selector(clickPriceBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:thirdBtn];
    [thirdBtn makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-23*ScaleX);
        make.top.mas_equalTo(chongzhiLab.mas_bottom).mas_equalTo(20*ScaleX);
        make.size.mas_equalTo(CGSizeMake(100*ScaleX, 34*ScaleX));
    }];
    
    UIButton *secodBtn = [[UIButton alloc] init];
    secodBtn.tag = 2002;
    self.secodBtn = secodBtn;
    [secodBtn setTitle:@"18乐学币" forState:UIControlStateNormal];
    
    secodBtn.backgroundColor = rgb(253,238,231);
    [self setupButton:secodBtn];
    
    [secodBtn addTarget:self action:@selector(clickPriceBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:secodBtn];
    [secodBtn makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(thirdBtn.mas_left).mas_equalTo(-15*ScaleX);
        make.left.mas_equalTo(firstBtn.mas_right).mas_equalTo(15*ScaleX);
        make.top.mas_equalTo(chongzhiLab.mas_bottom).mas_equalTo(20*ScaleX);
        make.height.mas_equalTo(34*ScaleX);
    }];
    
    
    // 第四个
    UIButton *fourthBtn = [[UIButton alloc] init];
    fourthBtn.tag = 2004;
    self.fourthBtn = fourthBtn;
    [fourthBtn setTitle:@"88乐学币" forState:UIControlStateNormal];
    
    fourthBtn.backgroundColor = rgb(253,238,231);
    [self setupButton:fourthBtn];
    [fourthBtn addTarget:self action:@selector(clickPriceBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.headerView addSubview:fourthBtn];
    [fourthBtn makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(23*ScaleX);
        make.top.mas_equalTo(firstBtn.mas_bottom).mas_equalTo(16*ScaleX);
        make.size.mas_equalTo(CGSizeMake(100*ScaleX, 34*ScaleX));
    }];
    //第六个
    
    UIButton *sixthBtn = [[UIButton alloc] init];
    sixthBtn.tag = 2006;
    self.sixthBtn = sixthBtn;
    [sixthBtn setTitle:@"128乐学币" forState:UIControlStateNormal];
    
    sixthBtn.backgroundColor = rgb(253,238,231);//rgb(233,84,18);
    [self setupButton:sixthBtn];
    [sixthBtn addTarget:self action:@selector(clickPriceBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.headerView addSubview:sixthBtn];
    [sixthBtn makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-23*ScaleX);
        make.top.mas_equalTo(thirdBtn.mas_bottom).mas_equalTo(16*ScaleX);
        make.size.mas_equalTo(CGSizeMake(100*ScaleX, 34*ScaleX));
    }];
    
    //第五个
    UIButton *fivethBtn = [[UIButton alloc] init];
    fivethBtn.tag = 2005;
    self.fivethBtn = fivethBtn;
    [fivethBtn setTitle:@"108乐学币" forState:UIControlStateNormal];
    
    fivethBtn.backgroundColor = rgb(253,238,231);
    [self setupButton:fivethBtn];
    [fivethBtn addTarget:self action:@selector(clickPriceBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:fivethBtn];
    [fivethBtn makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(sixthBtn.mas_left).mas_equalTo(-15*ScaleX);
        make.left.mas_equalTo(fourthBtn.mas_right).mas_equalTo(15*ScaleX);
        make.top.mas_equalTo(secodBtn.mas_bottom).mas_equalTo(16*ScaleX);
        make.height.mas_equalTo(34*ScaleX);
    }];
    
    //确认按钮
    UIButton *sureBtn = [[UIButton alloc] init];
    self.sureBtn = sureBtn;
    [sureBtn setBackgroundImage:[UIImage imageNamed:@"wk_shadow_btn"] forState:UIControlStateNormal];
    [sureBtn setTitle:@"确认支付（¥ 6.00）" forState:UIControlStateNormal];
    sureBtn.titleLabel.font = [UIFont systemFontOfSize:15*ScaleX];
    sureBtn.backgroundColor = rgb(253,238,231);
    sureBtn.layer.cornerRadius = 17*ScaleX;
    [sureBtn addTarget:self action:@selector(clickSureBtn:) forControlEvents:UIControlEventTouchUpInside];
    sureBtn.layer.masksToBounds = YES;
    [self.headerView addSubview:sureBtn];
    [sureBtn makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-15*ScaleX);
        make.left.mas_equalTo(15*ScaleX);
        make.top.mas_equalTo(fivethBtn.mas_bottom).mas_equalTo(30*ScaleX);
        make.height.mas_equalTo(44*ScaleX);
    }];
    //叹号充值说明
    UIImageView *alertImageView = [[UIImageView alloc] init];
    alertImageView.image = [UIImage imageNamed:@"wanke_czsm"];
    [self.headerView addSubview:alertImageView];
    [alertImageView makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15*ScaleX);
        make.top.mas_equalTo(sureBtn.mas_bottom).mas_equalTo(50*ScaleX);
        make.size.mas_equalTo(CGSizeMake(15*ScaleX, 15*ScaleX));
    }];
    
    UILabel *czsmLab = [UILabel labelWithText:@"充值说明" andTextColor:rgb(51,51,51) andName:nil andFontSize:16*ScaleX];
    [self.headerView addSubview:czsmLab];
    [czsmLab makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(alertImageView.mas_right).mas_equalTo(6*ScaleX);
        make.centerY.mas_equalTo(alertImageView);
    }];
    
    self.productID = @"courseIDA1";
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
}
#pragma mark - SKProductsRequestDelegate
-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
    if (response.invalidProductIdentifiers.count > 0) {
        [SVProgressHUD showErrorWithStatus:@"ProductID为无效ID"];
        return;
    }else{
        //取到内购产品进行购买
        SKMutablePayment *payment = [SKMutablePayment paymentWithProduct:response.products.firstObject];
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    }
}


#pragma mark - SKPaymentTransactionObserver
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
    for (SKPaymentTransaction *transaction in transactions)
    {
        switch (transaction.transactionState)
        {
            case SKPaymentTransactionStatePurchased://购买成功
                [self dl_completeTransaction:transaction];
                break;
            case SKPaymentTransactionStateFailed://购买失败
                [self dl_failedTransaction:transaction];
                break;
            case SKPaymentTransactionStateRestored://恢复购买
                [self dl_restoreTransaction:transaction];
                break;
            case SKPaymentTransactionStatePurchasing://正在处理
                break;
            default:
                break;
        }
    }
    
}


#pragma mark - PrivateMethod
- (void)dl_completeTransaction:(SKPaymentTransaction *)transaction {
    NSString *productIdentifier = transaction.payment.productIdentifier;
    NSString *transactionId = transaction.transactionIdentifier;
    
    //从沙盒中获取交易凭证
    NSURL *receiptUrl=[[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData=[NSData dataWithContentsOfURL:receiptUrl];
    //转化为base64字符串
    NSString *receiptString=[receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    //除去receiptdata中的特殊字符
    NSString *receipt1=[receiptString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSString *receipt2=[receipt1 stringByReplacingOccurrencesOfString:@"\r" withString:@""];
//    NSString *receipt3=[receipt2 stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
    //最终将这个receipt3的发送给服务器去验证就没问题啦！
    if ([receipt2 length] > 0 && [productIdentifier length] > 0) {
        [SVProgressHUD showSuccessWithStatus:@"支付成功"];
        /**
         可以将receipt发给服务器进行购买验证
         */
        NSString *token = [UserModel getUserModel].token;
        NSMutableDictionary *data = [NSMutableDictionary dictionary];
        [data setObject:token forKey:@"token"];
        [data setObject:self.resutltPrice forKey:@"productId"];
        [data setObject:transactionId forKey:@"transactionId"];
        [data setObject:receipt2 forKey:@"payload"];
        [self requestSeriveData:data receipt:receipt2];
        
    }else{
        
    }
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
- (void)requestSeriveData:(NSMutableDictionary*)data receipt:(NSString *)receipt{
    [WYHXNetWorkManager post:WKaApplePay_WKURL params:data completionHandler:^(id responseObj, NSError *error) {

        NSString *code = responseObj[@"code"];
        NSString *msg = responseObj[@"msg"];
        if ([code integerValue]==200) {
            [self checkRequesntServiceData];
            
        }else if ([code integerValue]==203){
            [SVProgressHUD showErrorWithStatus:@"支付失败"];
            [self sencodRequestSeriveData:data receipt:receipt];
            return ;
        }
    }];
}
- (void)sencodRequestSeriveData:(NSMutableDictionary*)data receipt:(NSString *)receipt{
    [WYHXNetWorkManager post:WKaApplePay_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
//        NSLog(@"responseObj====%@",responseObj);
//        NSLog(@"error====%@",error);
        NSString *code = responseObj[@"code"];
        NSString *msg = responseObj[@"msg"];
        if ([code integerValue]==200) {
            [self checkRequesntServiceData];
            
        }else if ([code integerValue]==203){
            [SVProgressHUD showErrorWithStatus:@"支付失败"];
            return ;
        }
    }];
}
- (void)dl_failedTransaction:(SKPaymentTransaction *)transaction {
    if(transaction.error.code != SKErrorPaymentCancelled) {
        [SVProgressHUD showErrorWithStatus:@"用户取消支付"];
    } else {
        [SVProgressHUD showErrorWithStatus:@"支付失败"];
    }
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

- (void)dl_restoreTransaction:(SKPaymentTransaction *)transaction {
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}



//结束后一定要销毁
- (void)dealloc
{
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}

- (void)setupButton:(UIButton *)sender{
    sender.layer.cornerRadius = 17*ScaleX;
    sender.layer.masksToBounds = YES;
    sender.titleLabel.font = [UIFont systemFontOfSize:15*ScaleX];
}

#pragma mark - 点击确认按钮
- (void)clickSureBtn:(UIButton *)sender{
    NSLog(@"确认支付");
    NSString *productID = self.productID;//self.productIDArray[indexPath.row];
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithArray:@[productID]]];
    request.delegate = self;
    [request start];
    [SVProgressHUD showWithStatus:@"正在加载"];
}
#pragma makr - 点击价格按钮
- (void)clickPriceBtn:(UIButton *)sender{
    NSInteger index = sender.tag-2000;
    
    switch (index) {
            
        case 1:
            NSLog(@"价格====%@",sender.currentTitle);
            self.firstBtn.backgroundColor = rgb(233,84,18);
            self.secodBtn.backgroundColor = rgb(253,238,231);
            self.thirdBtn.backgroundColor = rgb(253,238,231);
            self.fourthBtn.backgroundColor = rgb(253,238,231);
            self.fivethBtn.backgroundColor = rgb(253,238,231);
            self.sixthBtn.backgroundColor = rgb(253,238,231);
            [self.sureBtn setTitle:[NSString stringWithFormat:@"确认支付(%@)",[sender.currentTitle stringByReplacingOccurrencesOfString:@"乐学币" withString:@".00"]] forState:UIControlStateNormal];
            self.productID = [self.productIDArray objectAtIndex:index-1];
            self.resutltPrice = [NSString stringWithFormat:@"%@",[sender.currentTitle stringByReplacingOccurrencesOfString:@"乐学币" withString:@".00"]];
            break;
        case 2:
            NSLog(@"价格====%@",sender.currentTitle);
            self.secodBtn.backgroundColor = rgb(233,84,18);
            self.firstBtn.backgroundColor = rgb(253,238,231);
            self.thirdBtn.backgroundColor = rgb(253,238,231);
            self.fourthBtn.backgroundColor = rgb(253,238,231);
            self.fivethBtn.backgroundColor = rgb(253,238,231);
            self.sixthBtn.backgroundColor = rgb(253,238,231);
            [self.sureBtn setTitle:[NSString stringWithFormat:@"确认支付(%@)",[sender.currentTitle stringByReplacingOccurrencesOfString:@"乐学币" withString:@".00"]] forState:UIControlStateNormal];
            self.resutltPrice = [NSString stringWithFormat:@"%@",[sender.currentTitle stringByReplacingOccurrencesOfString:@"乐学币" withString:@".00"]];
            self.productID = [self.productIDArray objectAtIndex:index-1];
            break;
        case 3:
            NSLog(@"价格====%@",sender.currentTitle);
            self.thirdBtn.backgroundColor = rgb(233,84,18);
            self.firstBtn.backgroundColor = rgb(253,238,231);
            self.secodBtn.backgroundColor = rgb(253,238,231);
            self.fourthBtn.backgroundColor = rgb(253,238,231);
            self.fivethBtn.backgroundColor = rgb(253,238,231);
            self.sixthBtn.backgroundColor = rgb(253,238,231);
            [self.sureBtn setTitle:[NSString stringWithFormat:@"确认支付(%@)",[sender.currentTitle stringByReplacingOccurrencesOfString:@"乐学币" withString:@".00"]] forState:UIControlStateNormal];
            self.resutltPrice = [NSString stringWithFormat:@"%@",[sender.currentTitle stringByReplacingOccurrencesOfString:@"乐学币" withString:@".00"]];
            self.productID = [self.productIDArray objectAtIndex:index-1];
            break;
        case 4:
            NSLog(@"价格====%@",sender.currentTitle);
            self.fourthBtn.backgroundColor = rgb(233,84,18);
            self.firstBtn.backgroundColor = rgb(253,238,231);
            self.secodBtn.backgroundColor = rgb(253,238,231);
            self.thirdBtn.backgroundColor = rgb(253,238,231);
            self.fivethBtn.backgroundColor = rgb(253,238,231);
            self.sixthBtn.backgroundColor = rgb(253,238,231);
//NSString *strUrl = [urlString stringByReplacingOccurrencesOfString:@" " withString:@"/"];替换字符
            [self.sureBtn setTitle:[NSString stringWithFormat:@"确认支付(%@)",[sender.currentTitle stringByReplacingOccurrencesOfString:@"乐学币" withString:@".00"]] forState:UIControlStateNormal];
            self.resutltPrice = [NSString stringWithFormat:@"%@",[sender.currentTitle stringByReplacingOccurrencesOfString:@"乐学币" withString:@".00"]];
            self.productID = [self.productIDArray objectAtIndex:index-1];
            break;
        case 5:
            NSLog(@"价格====%@",sender.currentTitle);
            self.fivethBtn.backgroundColor = rgb(233,84,18);
            self.firstBtn.backgroundColor = rgb(253,238,231);
            self.secodBtn.backgroundColor = rgb(253,238,231);
            self.thirdBtn.backgroundColor = rgb(253,238,231);
            self.fourthBtn.backgroundColor = rgb(253,238,231);
            self.sixthBtn.backgroundColor = rgb(253,238,231);
            [self.sureBtn setTitle:[NSString stringWithFormat:@"确认支付(%@)",[sender.currentTitle stringByReplacingOccurrencesOfString:@"乐学币" withString:@".00"]] forState:UIControlStateNormal];
            self.resutltPrice = [NSString stringWithFormat:@"%@",[sender.currentTitle stringByReplacingOccurrencesOfString:@"乐学币" withString:@".00"]];
            self.productID = [self.productIDArray objectAtIndex:index-1];
            break;
        case 6:
            NSLog(@"价格====%@",sender.currentTitle);
            self.sixthBtn.backgroundColor = rgb(233,84,18);
            self.firstBtn.backgroundColor = rgb(253,238,231);
            self.secodBtn.backgroundColor = rgb(253,238,231);
            self.thirdBtn.backgroundColor = rgb(253,238,231);
            self.fourthBtn.backgroundColor = rgb(253,238,231);
            self.fivethBtn.backgroundColor = rgb(253,238,231);
            [self.sureBtn setTitle:[NSString stringWithFormat:@"确认支付(%@)",[sender.currentTitle stringByReplacingOccurrencesOfString:@"乐学币" withString:@".00"]] forState:UIControlStateNormal];
            self.resutltPrice = [NSString stringWithFormat:@"%@",[sender.currentTitle stringByReplacingOccurrencesOfString:@"乐学币" withString:@".00"]];
            self.productID = [self.productIDArray objectAtIndex:index-1];
            break;
            
            
        default:
            break;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
//    if (!cell) {
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
//    }
    ZSDTCoreTextCell *dtCell = (ZSDTCoreTextCell *) [self tableView:tableView prepareCellForIndexPath:indexPath];
    return dtCell;
    
}
#pragma mark - private Methods
//创建富文本单元格，并更新单元格上的数据
- (ZSDTCoreTextCell *)tableView:(UITableView *)tableView prepareCellForIndexPath:(NSIndexPath *)indexPath{
    NSString *key = [NSString stringWithFormat:@"dtCoreTextCellKEY%ld", (long)indexPath.row];
    ZSDTCoreTextCell *cell = [_cellCache objectForKey:key];
    
    if (!cell){
        //    cell = [self.tableView dequeueReusableCellWithIdentifier:_cellID_DTCoreText];
        //        if (!cell) {
        cell = [[ZSDTCoreTextCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:_cellID_DTCoreText];
        //        }
        cell.attributedTextContextView.edgeInsets = UIEdgeInsetsMake(0, 15, 0, 15);
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.hasFixedRowHeight = NO;
        cell.textDelegate = self;
        cell.attributedTextContextView.shouldDrawImages = YES;
        //记录在缓存中
        [_cellCache setObject:cell forKey:key];
    }
    //2.设置数据
    //2.1为富文本单元格设置Html数据
    [cell setHTMLString:self.htmlString];
    //2.2为每个占位图(图片)设置大小，并更新
    for (DTTextAttachment *oneAttachment in cell.attributedTextContextView.layoutFrame.textAttachments) {
        NSValue *sizeValue = [_imageSizeCache objectForKey:oneAttachment.contentURL];
        if (sizeValue) {
            cell.attributedTextContextView.layouter=nil;
            oneAttachment.displaySize = [sizeValue CGSizeValue];
            [cell.attributedTextContextView relayoutText];
        }
    }
    [cell.attributedTextContextView relayoutText];
    return cell;
}

#pragma mark - DTAttributedTextContentViewDelegate
//对于没有在Html标签里设置宽高的图片，在这里为其设置占位
- (UIView *)attributedTextContentView:(DTAttributedTextContentView *)attributedTextContentView viewForAttachment:(DTTextAttachment *)attachment frame:(CGRect)frame{
    if([attachment isKindOfClass:[DTImageTextAttachment class]]){
        ZSDTLazyImageView *imageView = [[ZSDTLazyImageView alloc] initWithFrame:frame];
        imageView.delegate = self;
        imageView.image = [(DTImageTextAttachment *)attachment image];
        imageView.textContentView = attributedTextContentView;
        imageView.url = attachment.contentURL;
        return imageView;
    }
    return nil;
}
//对于无宽高懒加载得到的图片，缓存记录其大小,然后执行表视图更新
- (void)lazyImageView:(ZSDTLazyImageView *)lazyImageView didChangeImageSize:(CGSize)size{
    BOOL needUpdate = NO;
    NSURL *url = lazyImageView.url;
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"contentURL == %@", url];
    /* update all attachments that matchin this URL (possibly multiple
     images with same size)
     */
    for (DTTextAttachment *oneAttachment in [lazyImageView.textContentView.layoutFrame textAttachmentsWithPredicate:pred]){
        // update attachments that have no original size, that also sets the display size
        if (CGSizeEqualToSize(oneAttachment.originalSize, CGSizeZero)){
            oneAttachment.originalSize = size;
            NSValue *sizeValue = [_imageSizeCache objectForKey:oneAttachment.contentURL];
            if (!sizeValue) {
                //将图片大小记录在缓存中，但是这种图片的原始尺寸可能很大，所以这里设置图片的最大宽
                //并且计算高
                CGFloat aspectRatio = size.height / size.width;
                CGFloat width = ZSToolScreenWidth - 15*2;
                CGFloat height = width * aspectRatio;
                CGSize newSize = CGSizeMake(width, height);
                [_imageSizeCache setObject:[NSValue valueWithCGSize:newSize]forKey:url];
            }
            needUpdate = YES;
        }
    }
    
    if (needUpdate){
        //有新的图片尺寸被缓存记录的时候，需要刷新表视图
        //[self reloadCurrentCell];
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(reloadCurrentCell) object:nil];
        self.isScrolling = NO;
        [self performSelector:@selector(reloadCurrentCell) withObject:nil afterDelay:0.2];
    }
}
- (void)reloadCurrentCell{
    //如果当前表视图在滑动就不执行刷新，因为滑动时候会自动调用表视图的刷新方法
    if (self.isScrolling) {
        return;
    }
    //如果当前表视图没有在滑动，就手动刷新当前在屏幕显示的单元格
    NSArray *indexPaths = [self.tableView indexPathsForVisibleRows];
    if(indexPaths){
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
        });
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    _isScrolling = YES;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return 0.001;
    ZSDTCoreTextCell *cell = (ZSDTCoreTextCell *)[self tableView:tableView prepareCellForIndexPath:indexPath];
    return [cell requiredRowHeightInTableView:tableView];
}



- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    return NO;
    
}

//-(void)dl_validateReceiptWiththeAppStore:(NSString *)receipt
//{
//    NSError *error;
//    NSDictionary *requestContents = @{@"receipt-data": receipt};
//    NSData *requestData = [NSJSONSerialization dataWithJSONObject:requestContents options:0 error:&error];
//
//    if (!requestData) {
//
//    }else{
//
//    }
//    NSURL *storeURL;
//#ifdef DEBUG
//    storeURL = [NSURL URLWithString:@"https://sandbox.itunes.apple.com/verifyReceipt"];
//#else
//    storeURL = [NSURL URLWithString:@"https://buy.itunes.apple.com/verifyReceipt"];
//#endif
//
//    NSMutableURLRequest *storeRequest = [NSMutableURLRequest requestWithURL:storeURL];
//    [storeRequest setHTTPMethod:@"POST"];
//    [storeRequest setHTTPBody:requestData];
//    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//    [NSURLConnection sendAsynchronousRequest:storeRequest queue:queue
//                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//                               if (connectionError) {
//                                   /* 处理error */
//                               } else {
//                                   NSError *error;
//                                   NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
//                                   if (!jsonResponse) {
//                                       /* 处理error */
//                                   }else{
//                                       /* 处理验证结果 */
//                                       NSLog(@"%@",jsonResponse);
//                                   }
//                               }
//                           }];
//
//}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
